package cn.com.suiyi.shixingshengxian.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import java.util.List;

import cn.com.suiyi.shixingshengxian.R;
import cn.com.suiyi.shixingshengxian.active.ActiveFragment;
import cn.com.suiyi.shixingshengxian.classify.ClassifyFragment;
import cn.com.suiyi.shixingshengxian.home.HomeFragment;
import cn.com.suiyi.shixingshengxian.mine.MineFragment;
import cn.com.suiyi.shixingshengxian.shopping.ShoppingFragment;

/**
 * Created by Administrator on 2016/7/20.
 */

/**
 * 底部导航工具类
 */
public class BottomTabManager {
    List<Fragment> fragments;
    FragmentManager manager;
    private int containerId;

    public BottomTabManager(List<Fragment> fragments, int containerId, FragmentManager manager) {
        this.fragments = fragments;
        this.containerId = containerId;
        this.manager = manager;
    }

    /**
     * 得到fragmenttransaction对象
     *
     * @return
     */
    private FragmentTransaction getFragmentTransaction() {
        FragmentTransaction ft = null;
        if (ft == null) {
            ft=manager.beginTransaction();
        }
        return ft;
    }

    //设置fragment选择
    public  void setSelection(int index) {
        hideFragments(getFragmentTransaction());
        for (int i = 0; i < fragments.size(); i++) {
            Fragment fragment = fragments.get(i);
            if (index == i) {
                if (!fragment.isAdded()) {
                    getFragmentTransaction().add(containerId, fragment).commit();
                }
                if (fragment.isHidden()) {
                    getFragmentTransaction().show(fragment).commit();
                }
                if (listener != null) {
                    listener.onBottomTabSelectListener(index, fragments.size());
                }
            } else {
                //隐藏
                getFragmentTransaction().hide(fragment).commit();
            }
        }
    }

    //隐藏Fragment
    private void hideFragments(FragmentTransaction transaction) {
        for (int i = 0; i < fragments.size(); i++) {
            if (fragments.get(i) != null) {
                transaction.hide(fragments.get(i));
            }
        }
    }
    public interface OnBottomTabSelectListener {
        void onBottomTabSelectListener(int index, int count);

    }
   private  OnBottomTabSelectListener listener;

    public void setListener(OnBottomTabSelectListener listener) {
        this.listener = listener;
    }
}
